<?php

namespace App\Http\Controllers\ZHIHU\Common;

use Response;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
use Carbon\Carbon;
use App\Eloqumd\Zhihu\ZhihuTopic;
use App\Http\Controllers\ZHIHU\Systems\SystemsConfigController as SCC;

class ShareController extends Controller
{
    private	static $_instance;
    
    public static function getInstance()
    {
    	if (! (self::$_instance instanceof self)) {
    		self::$_instance = new self();
    	}
    	
    	return self::$_instance;
    }
    
    public function getDirtyWords()
    {
        if (is_null($configVal = SCC::getting('dirty'))) {
            return [];
        }

        if ($dirtyName = $configVal['dirtyName']) {
            return explode(',', $dirtyName);
        } else {
            return [];
        }
    }

    public function topicSelectDict()
    {
        return ZhihuTopic::select('id as value', 'name as label')->where('status', 1)->get()->toArray();
    }

    public function initQNBucket($init = 'up', $key = '')
    {
        $accessKey = '6-vR074y9LIQ733kgycjSN_kX75l0MxTFLE9myWJ';
        $secretKey = 'jvD9W5Bn0C-lUgaqZxgTgUyrq9kSVmP_6CWNGTwX';
        $bucket = 'jishulin';
        $qnurl = 'http://qb4yo9ydu.bkt.clouddn.com/';
        $auth = new Auth($accessKey, $secretKey);
        if ($init == 'up') {
            $key = empty($key) ? (Carbon::now()->toW3cString() . '-' .  session_create_id()) : $key;
            $token = $auth->uploadToken($bucket);
            $uploadMgr = new UploadManager();

            return [$uploadMgr, $token, $key];
        } elseif ($init == 'vf') {
            $config = new \Qiniu\Config();
            $bucketManager = new BucketManager($auth, $config);

            return list($fileInfo, $err) = $bucketManager->stat($bucket, $key);
        } elseif ($init == 'vv') {
            return $qnurl . urlencode($key);
        }
    }

    public function initQTCucket($init = 'up', $key = '')
    {
        $secretId = "AKID71g6HCnZOxKTLx8VWJtEKBoFTYNBm8F6";
        $secretKey = "pQnvztXxi16EHE7vXwkgNo31vgHdmiPt";
        $region = "ap-nanjing";
        $bucket = "jishulin-1258682100";
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'http',
                'credentials'=> array(
                    'secretId'  => $secretId ,
                    'secretKey' => $secretKey
                )
            )
        );

        if ($init == 'up') {
            $key = empty($key) ? (Carbon::now()->toW3cString() . '-' .  session_create_id()) : $key;
            return [$cosClient, $bucket, $key];
        } elseif ($init == 'vv') {
            return $signedUrl = $cosClient->getObjectUrl($bucket, $key, '+5256000 minutes');
        }
    }
    
    public function getSrcByKey($key)
    {
        return $this->initQTCucket('vv', $key);
    }
    
    public function imageUpload(Request $request)
    {
        if (false === $file = $this->checkFile($request)) {
            return Response::json(['code' => 50000, 'message' => trans('zhihu.Upload-Error')]);
        }
        $fileExtension = strtolower($file->getClientOriginalExtension());
        $filePath = $file->getRealPath();
        $files = fopen($filePath, "rb");
        list($cosClient, $bucket, $key) = $this->initQTCucket();

        $uploadKey = $key . '.' .$fileExtension;

        try {
            $result = $cosClient->putObject(array(
                'Bucket' => $bucket,
                'Key' => $uploadKey,
                'Body' => $files
            ));
            // print_r($result);

            $finalKey = $result['Key'];

            $signedUrl = $cosClient->getObjectUrl($bucket, $finalKey, '+5256000 minutes');

            return Response::json(['code' => 10000, 'message' => '', 'data' => [
                'name' => $finalKey,
                'url' => $signedUrl
            ]]);
        } catch (\Exception $e) {
            return Response::json(['code' => 50000, 'message' => $e->getMessasge()]);
        }

        // list($uploadMgr, $token, $key) = $this->initQNBucket();

        // $uploadKey = $key . '.' .$fileExtension;

        // list($ret, $err) = $uploadMgr->putFile($token, $uploadKey, $filePath);

        // if ($err !== null) {
        //     return Response::json(['code' => 50000, 'message' => $err]);
        // }

        // $view = $this->initQNBucket('vv', $ret['key']);

        // return Response::json(['code' => 10000, 'message' => '', 'data' => [
        //     'name' => $ret['key'],
        //     'url' => $view
        // ]]);
    }

    public function checkFile($request)
    {
        $file = null;
        $tag = null;
        if ($request->hasFile('file')) {
            $file = $request->file('file');
        } elseif ($request->hasFile('images')) {
            $file = $request->file('images');
        } elseif ($request->hasFile('editormd-image-file')) {
            $file = $request->file('editormd-image-file');
            $tag = 'md';
        } elseif ($request->hasFile('image')) {
            $file = $request->file('image');
        } elseif ($request->hasFile('img')) {
            $file = $request->file('img');
        }

        // 不存在上传文件信息
        if (is_null($file)) {
            return false;
        }

        // 判断文件是否有效
        if (!$file->isValid()) {
            return false;
        }

        return $file;
    }
}
